var chat={
	_soundSwf:null,
	_msgUrl : "/message/dmsgs.htm?driverId=",
	_sendUrl:"/message/chat.htm",
	_lastId : 0,
	_receiveId : 0,
	_userType :0,//1乘客,2司机
	
	_soundUrl : "/message/sound.htm?fileId=",
	soundPlatLoaded:function(){
		if (navigator.appName.indexOf("Microsoft")!= -1) {  
			chat._soundSwf = window["swfChatComponent"];  
		} else {  
			chat._soundSwf = document["swfChatComponent"];  
		} 
		$("#btnRecord").click(function(e) {
			chat.record();
        });
		$("#btnRecord").val("开始录音");
	},
	createIcon:function(receiveId, userType){
		document.write("<a class='msg' href='javascript:chat.openChat("+receiveId+","+userType+")' title='和对方聊天'>对话</a>");
	},
	openChat:function(receiveId, userType){
		if(!receiveId || !userType) {
			alert('参数错误无法对话');
			return;
		}
		//计算map的宽高
		var w = $(window).width() - 80;
		var h = $(window).height() - 140;
		
		var url = root+"/message/chat.htm?receiveId=" + receiveId+"&userType="+userType;
		qBox.iFrame({title:'一对一对话',w:w,h:h,src:url})
	},
	soundLoaded:function(){
		if(chat._soundSwf)chat._soundSwf.play();
	},
	soundPlayCompleted:function(){
		alert("放完了");
	},
	playSound:function(id){
		if(chat._soundSwf){
			var url = root + chat._soundUrl+id;
			chat._soundSwf.load(url+"&"+Date.parse(new Date()));
		}
	},
	loadMessages:function(receiveId,userType){
		if(receiveId)chat._receiveId = receiveId;
		if(userType)chat._userType = userType;
	
		var url = root+chat._msgUrl+chat._receiveId;
		if(chat._lastId>0){
			url = url+"&lastId="+chat._lastId;
		}
		chat.loadData(url,function(dat){
			for(var idx=dat.length-1; idx>=0;idx--){
				var d= dat[idx];
				if(parseInt(d._id)>chat._lastId){
					chat._lastId = parseInt(d._id)
				}
				var chatItem =[];
				if(d.sender==0){
					chatItem.push('<div class="chatListItem" style="text-align:right">');
					chatItem.push('<div>');
					chatItem.push('我'+ d.time);
					chatItem.push('</div><span>');
				}else if(d.sender==1){
					chatItem.push('<div class="chatListItem" style="text-align:left">');
					chatItem.push('<div >');
					
					chatItem.push(chat.dname +'  '+ d.time);
					chatItem.push('</div><span>');
				}
				if(d.type==1){
					chatItem.push(d.txt);
				}else if(d.type==2){
					chatItem.push('<a href="javascript:chat.playSound('+d.fid+');">播放('+d.length+'秒)</a>');
				}else if(d.type==3){
					chatItem.push("图片:"+d.fid);
				}
				chatItem.push('</span> </div>');
				$("#idChatList").append(chatItem.join(""));
				$('#idChatList').animate({scrollTop: $('#idChatList').prop("scrollHeight")}, 0);
			}
		});
	},
	send:function(){
		var content = $("#txtSend").val();
		var chatItem =[];
					chatItem.push('<div class="chatListItem" style="text-align:right">');
					chatItem.push('<div>');
					chatItem.push('我 '+ chat.currTime());
					chatItem.push('</div><span>');
		chatItem.push(content);
		chatItem.push('</span> </div>');
		$("#idChatList").append(chatItem.join(""));
			$('#idChatList').animate({scrollTop: $('#idChatList').prop("scrollHeight")}, 100);
		$("#txtSend").val("");
		//var url = root + chat._sendUrl +chat._receiveId+"&content="+encodeURI(content)+"&pushType="+chat._userType;
		var url = root + chat._sendUrl+"?type=1&did="+chat._receiveId+"&msg="+encodeURI(content);
		chat.loadData(url,function(dat){
			$("#idChatInput").val("");
		});
	},
	/*---录音-----------*/
	recordStarted:function(){
		$("#btnRecord").attr("states",1);
		$("#btnRecord").val("停止录音");
	},
	getRecordParams:function(){
		return {
			url:root + chat._sendUrl,
			data:{
				did:chat._receiveId,
				type:2
			}
		};
	},
	recordCompleted:function(msg){
		$("#btnRecord").attr("states",0);
		$("#btnRecord").val("开始录音");
		if(msg!=""){
			alert(msg);
		}
	},
	record:function(){
		var states = $("#btnRecord").attr("states");
		if(states==-1){
			alert("正则处理，请稍候....");
		}else if(states==1){
			$("#btnRecord").attr("states",-1);
			$("#btnRecord").val("正在保存...");
			chat._soundSwf.recordStop();
		}else{
			chat._soundSwf.recordStart();
		}
	},
	loadData:function(url, onSucc,method){
		if(!method) method = 'GET';
		jQuery.ajax({
			type :method,
			contentType : 'text/html',
			url : url,
			success : function(data) {
				if(onSucc){
					onSucc(data);
				}
			},
			error : function(data) {
					//alert(data)
			}
		});
	},
	currTime:function(){
		var d = new Date();
		return (d.getMonth() + 1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes()+'-'+ d.getSeconds(); 
	},
	sizeFit:function(){
		//计算map的宽高
		var w = $("#idChat").width() - 4;
		var h = $(window).height()- $("#idChatInput").height() - 20;
		
		var hBtn =  $("#idChatInput").height() -4;
		var wTxt = $("#idChatInput").width() - hBtn -120;
		
		$("#idChatBody").width(w);
		$("#idChatBody").height(h);
		$("#idChatList").width(w- $("#idUserInfo").width()- 4);
		$("#idChatList").height(h-4);
		$("#idUserInfo").height(h-4);
		$("#txtSend").width(wTxt);
		$("#btnSend").css({width:hBtn,height:hBtn,"line-height":hBtn+"px"});
	},
	init:function(){
		if(typeof(swfobject)!='undefined'){
			chat.sizeFit();
			$(window).resize(function(e) {
				chat.sizeFit();
				
			});
			swfobject.embedSWF(
				root+"/res/img/ShareachSound.swf?aa",
				"swfChatComponent",  
				"6", "3", "9.0.0", "expressInstall.swf",  "",   
			  {"wmode":"transparent","quality":"high","allowscriptaccess":"sameDomain","allowfullscreen":"true"}  
			);
			$("#btnSend").bind("click",function(){
				chat.send();
			});
			setInterval(function(){
				chat.loadMessages();
			},2000);
			$("#txtSend").bind("keypress",function(e){
				if (e.keyCode == 13) {
					chat.send();
				}
			});
		}
	}
}


$(document).ready(function(){
	chat.init();
		
	$("#checkAll").click(function(){
			var allCheck = this;
			$(".check_mobile").each(function(){
				this.checked = allCheck.checked;
			})
		});
		
		$("#select_mobiles_btn").click(function(){
			var mobiles = [];
			$(".check_mobile").each(function(){
				if (this.checked || this.checked == 'true') {
					mobiles.push($(this).attr("data-ref"));
				}
			});
			var mobile_content = window.parent.document.getElementById("receiveIds");
		
			var old = $.trim(mobile_content.value);
		
		// 避免重复包含号码
		if (old) {
			var newMobiles = [];
			var oldMobiles = old.split(/\s+/);
			for (var i = 0; i < mobiles.length; i++) {
				var flag = true;
				var one = $.trim(mobiles[i]);
				for (var j = 0; j < oldMobiles.length; j++) {
					if (one == $.trim(oldMobiles[j])) {
						flag = false;
						break;
					}	
				}
				if (flag) {
					newMobiles.push(one);
				}
			}
			
		
				mobile_content.value = old + " " + newMobiles.join(" ");
			
		} else {
			mobile_content.value = mobiles.join(" ");
		}
	});

});